<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
</head>
<title>energy</title>
<link rel="stylesheet" type="text/css" th:href="@{/plugins/layui/css/layui.css}"/>
<script type="text/javascript" th:src="@{/javascript/jquery-2.1.4.js}"></script>
<script type="text/javascript" th:src="@{/plugins/layui/layui.js}"></script>
<style>
    body{margin: 10px;}
    .success{
        background-color: #b9947a;
    }
    .layui-table-box{
        max-height: 400px;
        overflow: scroll;
    }
    .demo-carousel{height: 200px; line-height: 200px; text-align: center;}
    .site-demo-laytpl {
        display: inline-block;
        text-align: center;
        width: 35%;
    }
    .site-demo-laytpl textarea {
        height: 300px;
        border: none;
        background-color: #3F3F3F;
        color: #E3CEAB;
        font-family: Courier New;
        resize: none;
    }
    .site-demo-laytpl div span {
        display: inline-block;
        text-align: center;
        background: #101010;
        color: #fff;
    }
    .site-demo-laytpl textarea, .site-demo-laytpl div span {
        width: 100%;
        padding: 15px;
        margin: 0 15px;
    }
</style>
<html>
<body>
<div class="layui-col-md12" style="line-height:50px; color:#fff;background-color: #FF5722!important;">
    <div class="grid-demo grid-demo-bg12" style="padding-left: 50px;">真实数据:「即取自smart_energy库中的数据,不在此模块下做实际修改操作。以下json属性值解析自smart_energy数据库」</div>
</div>
<div style="padding-top: 50px">
    <table id="iot" lay-filter="iot"></table>
    <div id="selectDown" style="padding-left: 15px;margin-bottom:10px;">
<!--        <button class="layui-btn productServiceList" style="display: none" id="productServiceList">-->
<!--            下拉菜单-->
<!--            <i class="layui-icon layui-icon-down layui-font-12"></i>-->
<!--        </button>-->
    </div>
    <div class="site-demo-laytpl">
        <div>
            <span>定时任务模拟数据模版</span>
            <!--        <span>result</span>-->
        </div>
        <textarea class="site-demo-text" style="width: 100%;float: left" id="data"></textarea>
        <textarea class="site-demo-text" style="display: none" id="tpl">
<div id="f1" class="layui-fluid" style="width:1500px;">
        <h3 style="padding: 15px;background: #e2e2e2;  text-align: center;  font-weight: 400;" >解析属性值:{{d.body.serviceId}}</h3>
        <input style="display: none" id="serviceId_parse" value="{{ d.body.serviceId}}" disabled>
        <div style="height:325px; overflow: scroll;background-color: #2d6e6a;">
            <ul>
                {{#  layui.each(d.servicePropertiesList, function(index, item){ }}
                <li style="">
                    <form id="{{ item.modname }}">
                        <div style="height: 50px;line-height: 50px;background-color: #203a38;"><span style="padding-left: 10px;font-weight: 500;color: #c7a7a7">参数名：{{ item.modname }}</span></div>
                        <div style="height: 50px;line-height: 50px;padding: 5px; background-color: #63b8b3;">
                            <input style="display: none"  name="{{ 'default_'+item.modname  }}" value="{{ item.alias }}">
                            <input disabled="disabled" style="width: 50px"  name="{{ 'dataType_'+item.modname  }}" value="{{ item.dataType }}">
                            <span name="{{ 'default_'+item.modname  }}" style="color: #3b0202;margin-right: 10px;">默认值：{{ item.alias }}</span>
                            {{# if(item.enable==1||item.enable==undefined||item.enable==null){ }}
                            开启随机: <input name="{{ 'random_enable_'+item.modname  }}"  style="margin-right: 10px;" type="checkbox" value="1"  checked>
                            {{# }else{ }}
                            开启随机: <input name="{{ 'random_enable_'+item.modname  }}"  style="margin-right: 10px;" type="checkbox" value="0">
                            {{# } }}
                            {{#  if( item.modname.includes('SOC') ){ }}
                                <input name="{{ 'random_trend_'+item.modname  }}"  style="display: none"  value="{{item.trend==null?1:item.trend}}" >
                                <select id="select" onchange="selectChange({{ 'random_trend_'+item.modname }},this)">
                                    {{#  if(item.trend== -1){ }}
                                    <option value="1" >递增↑</option>
                                    <option value="-1" selected>递减↓</option>
                                    {{#  }else{ }}
                                    <option value="1" selected>递增↑</option>
                                    <option value="-1">递减↓</option><option value="1" >递增↑</option>
                                {{#  } }}
                            </select>
                            {{# }}
                            步长: <input  style="width: 50px;" type="number" name="{{ 'random_size_'+item.modname  }}" value="{{item.size}}">
                            随机数Min: <input  style="width: 100px;" type="number" name="{{ 'random_min_'+item.modname  }}" value="{{ item.min }}">
                            随机数Max: <input style="width: 100px;" type="number" name="{{ 'random_max_'+item.modname  }}" value="{{ item.max }}">
                            {{#  }else{ }}
                            随机数Min: <input  style="width: 100px;" type="number" name="{{ 'random_min_'+item.modname  }}" value="{{ item.min }}">
                            随机数Max: <input style="width: 100px;" type="number" name="{{ 'random_max_'+item.modname  }}" value="{{ item.max }}">
                            {{#  } }}
                            {{# if(item.enum_enable==1){ }}
                            随机时使用以下枚举: <input name="{{ 'random_enable_enumList_'+item.modname  }}"  style="margin-right: 10px;" type="checkbox" value="1"  checked>
                            {{# }else{ }}
                            随机时使用以下枚举: <input name="{{ 'random_enable_enumList_'+item.modname  }}"  style="margin-right: 10px;" type="checkbox" value="0">
                            {{# } }}
<!--                            <input name="{{ 'random_enum_'+item.modname  }}"  style="display: none"  value="0"  >-->
                            <select style="width: 50px;" id="{{ 'random_enable_enumList_select_'+item.modname  }}" onchange="">
                                {{#  layui.each(item.enumList, function(index, item2){ }}
                                <option value="{{item2}}" >{{item2}}</option>
                                {{# });}}
                            </select>
                            <a style="background-color: #203a38"  id="{{'add_'+item.modname}}" class="layui-btn layui-btn-xs layui-btn-normal" onclick="addEnumInput({{item.modname}},this)">添加枚举值</a>
                        </div>
                    </form>
                </li>
                {{#  }); }}
                {{#  if(d.servicePropertiesList.length === 0){ }}
                ⽆数据
                {{#  } }}
            </ul>
        </div>
    </div>
    </textarea>
    </div>
    <div id="view" style="width: 60%;float: right;overflow: scroll;"></div>
</div>


<script id="demo" type="text/html">
    <div id="f1" class="layui-fluid" style="width:1500px;">
        <h3 style="padding: 15px;background: #e2e2e2;  text-align: center;  font-weight: 400;" >解析属性值:{{d.body.serviceId}}</h3>
        <input style="display: none" id="serviceId_parse" value="{{ d.body.serviceId}}" disabled>
        <div style="height:325px; overflow: scroll;background-color: #2d6e6a;">
            <ul>
                {{#  layui.each(d.servicePropertiesList, function(index, item){ }}
                <li style="">
                    <form id="{{ item.modname }}">
                        <div style="height: 50px;line-height: 50px;background-color: #203a38;"><span style="padding-left: 10px;font-weight: 500;color: #c7a7a7">参数名：{{ item.modname }}</span></div>
                        <div style="height: 50px;line-height: 50px;padding: 5px; background-color: #63b8b3;">
                            <input style="display: none"  name="{{ 'default_'+item.modname  }}" value="{{ item.alias }}">
                            <input disabled="disabled" style="width: 50px"  name="{{ 'dataType_'+item.modname  }}" value="{{ item.dataType }}">
                            <span name="{{ 'default_'+item.modname  }}" style="color: #3b0202;margin-right: 10px;">默认值：{{ item.alias }}</span>
                            {{# if(item.enable==1||item.enable==undefined||item.enable==null){ }}
                            开启随机: <input name="{{ 'random_enable_'+item.modname  }}"  style="margin-right: 10px;" type="checkbox" value="1"  checked>
                            {{# }else{ }}
                            开启随机: <input name="{{ 'random_enable_'+item.modname  }}"  style="margin-right: 10px;" type="checkbox" value="0">
                            {{# } }}
                            {{#  if( item.modname.includes('SOC') ){ }}
                                <input name="{{ 'random_trend_'+item.modname  }}"  style="display: none"  value="{{item.trend==null?1:item.trend}}" >
                                <select id="select" onchange="selectChange({{ 'random_trend_'+item.modname }},this)">
                                    {{#  if(item.trend== -1){ }}
                                    <option value="1" >递增↑</option>
                                    <option value="-1" selected>递减↓</option>
                                    {{#  }else{ }}
                                    <option value="1" selected>递增↑</option>
                                    <option value="-1">递减↓</option><option value="1" >递增↑</option>
                                {{#  } }}
                            </select>
                            {{# }}
                            步长: <input  style="width: 50px;" type="number" name="{{ 'random_size_'+item.modname  }}" value="{{item.size}}">
                            随机数Min: <input  style="width: 100px;" type="number" name="{{ 'random_min_'+item.modname  }}" value="{{ item.min }}">
                            随机数Max: <input style="width: 100px;" type="number" name="{{ 'random_max_'+item.modname  }}" value="{{ item.max }}">
                            {{#  }else{ }}
                            随机数Min: <input  style="width: 100px;" type="number" name="{{ 'random_min_'+item.modname  }}" value="{{ item.min }}">
                            随机数Max: <input style="width: 100px;" type="number" name="{{ 'random_max_'+item.modname  }}" value="{{ item.max }}">
                            {{#  } }}
                            {{# if(item.enum_enable==1){ }}
                            随机时使用以下枚举: <input name="{{ 'random_enable_enumList_'+item.modname  }}"  style="margin-right: 10px;" type="checkbox" value="1"  checked>
                            {{# }else{ }}
                            随机时使用以下枚举: <input name="{{ 'random_enable_enumList_'+item.modname  }}"  style="margin-right: 10px;" type="checkbox" value="0">
                            {{# } }}
<!--                            <input name="{{ 'random_enum_'+item.modname  }}"  style="display: none"  value="0"  >-->
                            <select style="width: 50px;" id="{{ 'random_enable_enumList_select_'+item.modname  }}" onchange="">
                                {{#  layui.each(item.enumList, function(index, item2){ }}
                                <option value="{{item2}}" >{{item2}}</option>
                                {{# });}}
                            </select>
                            <a style="background-color: #203a38"  id="{{'add_'+item.modname}}" class="layui-btn layui-btn-xs layui-btn-normal" onclick="addEnumInput({{item.modname}},this)">添加枚举值</a>
                        </div>
                    </form>
                </li>
                {{#  }); }}
                {{#  if(d.servicePropertiesList.length === 0){ }}
                ⽆数据
                {{#  } }}
            </ul>
        </div>
    </div>
</script>

<script th:inline="none" type="text/javascript">
    var jsonParse = {};
    var  layer = layui.layer //弹层
        ,laypage = layui.laypage //分页
        ,laydate = layui.laydate //日期
        ,table = layui.table //表格
        ,carousel = layui.carousel //轮播
        ,upload = layui.upload //上传
        ,element = layui.element //元素操作
        ,slider = layui.slider //滑块
        ,dropdown = layui.dropdown //下拉菜单
        ,laytpl=layui.laytpl;
    let productList = [];
    let propList = {};
    let propJson = {};
    let jsonBodyStr = `{
  "body":
  {
    "serviceId":"analog",
    "serviceProperties":
    {
      "ALIV_B2C_BMS":5,
      "BMS_Charge_Energe":107.7,
      "BMS_Current":0,
      "BMS_Discharge_Energe":105.5,
      "BMS_Hv":645.5,
      "BMS_Limit_Charge_Current":20,
      "BMS_Limit_Charge_Hv":904.4,
      "BMS_Limit_Discharge_Current":0,
      "BMS_Limit_Discharge_Hv":618.8,
      "BMS_PowerOn":0,
      "BMS_SOC":49.6,
      "BMS_SOH":100,
      "BMS_Status":4,
      "Cell_MaxTemp":10,
      "Cell_MaxVoltage":3303,
      "Cell_MinTemp":9,
      "Cell_MinVoltage":3301,
      "Protocol_Version":51,
      "Tank_Num_RelayOn":0
    }
  },
  "token":"9c0ca881-eac8-463e-8989-db0059fe3ded",
  "timestamp":"2022-05-01T15:35:07Z"
}`;
    $('#data').append(jsonBodyStr);

    function getParsingData(name,alias){
        let jsonItem ={};
        let max = 100;
        let min = 0;
        let enumList = [];
        let step = 0;
        let size = 0;
        let required = 1;
        let dataType = "decimal";
        let enum_enable = 0;
        let enable = 1;
        if(propList.length>0){
            try {
                propList.forEach(function(item,index){
                    if(item.propertyName == name){
                        max = item.max!=null?item.max:max;
                        min = item.min!=null?item.min:min;
                        enumList = item.enumList!=null?JSON.parse(item.enumList):enumList;
                        enum_enable = item.enum_enable!=null?item.enum_enable:enum_enable;
                        step = item.step!=null?item.step:step;
                        size = item.size!=null?item.size:size;
                        required = item.required!=null?item.required:required;
                        dataType = item.dataType!=null?item.dataType:dataType;
                        enable = item.enable!=null?item.enable:enable;
                        // throw new Error("");
                    }
                });
            }catch (e) {
                throw new Error("解析失败");
            };
        }
        jsonItem = {
            'modname':name,
            'alias':alias,
            'max':max,
            'min':min,
            'enumList':enumList,
            'enum_enable':enum_enable,
            'step':step,
            'size':size,
            'required':required,
            'enable':enable,
            'dataType':dataType
        }
        console.log(name,jsonItem);
        return jsonItem;
    };
    function controller(){
        console.log("jsonParse",jsonParse)
        try{
            let servicePropertiesList = [];
            // 解析模版
            let serviceProperties = JSON.parse(data.value).body.serviceProperties;
            for(var p in serviceProperties){//遍历json对象的每个key/value对,p为ke
                servicePropertiesList.push(getParsingData(p,serviceProperties[p]));
            }
            let json = JSON.parse(data.value);
            json['servicePropertiesList'] = servicePropertiesList;
            console.log("json",json);
            var html = laytpl(tpl.value).render(json);
            view.innerHTML = html;
        } catch(e){
            view.innerHTML = '<span style="color: #c00;">'+ e.toString() + '</span>';
        }
    };

    $(function () {
        //加载模块
        layui.use(['layer', 'laytpl','table'],function(){ //亦可加载特定模块：layui.use(['layer', 'laydate', function(){// //得到各种内置组件

            //数据模版实时解析===============================
            var view = document.getElementById('view')
            //     ,controller = function(){
            //     try{
            //         let servicePropertiesList = [];
            //         // 解析模版
            //         let serviceProperties = JSON.parse(data.value).body.serviceProperties;
            //         for(var p in serviceProperties){//遍历json对象的每个key/value对,p为ke
            //             servicePropertiesList.push(getParsingData(p,serviceProperties[p]));
            //         }
            //         let json = JSON.parse(data.value);
            //         json['servicePropertiesList'] = servicePropertiesList;
            //         console.log("json",json);
            //         var html = laytpl(tpl.value).render(json);
            //             view.innerHTML = html;
            //     } catch(e){
            //         view.innerHTML = '<span style="color: #c00;">'+ e.toString() + '</span>';
            //     }
            // };
            controller();
            layui.each(document.getElementsByTagName('textarea'), function(index, item){
                item.onkeyup = function(){
                    controller();
                }
            });
            //数据模版实时解析===============================

            function getIotProductService(id,serviceId){
                $('#selectDown').css('display','none');
                $.get(`/energy/iot/getIotProductService/${id}`,function(data,status){
                    if(data.code == 0){
                        console.log(data.data);
                        productList = data.data;
                        $('#selectDown').empty();
                        if (productList.length > 0) {
                            let html = `<button class="layui-btn" id="productServiceList">服务列表`
                                +`<i class="layui-icon layui-icon-down layui-font-12"></i>`
                                +`</button>`
                                +`<button type="button" id = "iotJsonList" onclick="openIotJsonList()" class="layui-btn layui-btn-normal">选择iot测试模版</button>`
                                +`<button type="button" id = "saveJson" onclick="saveJson()"  class="layui-btn layui-btn-warm">保存当前配置到iot测试模块</button>`
                            let dropdownList = [];
                            productList.forEach(function(item,index){
                                let id = item.id;
                                let serviceType = item.serviceType;
                                let description = item.description;
                                let itemJson = {
                                    id:id,
                                    title:serviceType+"-"+description
                                };
                                dropdownList.push(itemJson);
                            });
                            let liDom =  $(html);
                            $("#selectDown").append(liDom);
                            $('#selectDown').css('display','block');
                            dropdown.render({
                                elem: '#productServiceList'
                                ,data: dropdownList
                                ,click: function(obj){
                                    console.log(obj);
                                    layer.tips('选择了：'+ obj.title+' 解析数据如下', this.elem, {tips: [1, '#5FB878']});
                                    getProp(obj.id,obj.title.indexOf('-')>-1?obj.title.split('-')[0]:obj.title);
                                }
                            });
                        }
                    }else{
                        layer.msg("product信息获取失败", function(){
                        });
                    }
                });
            };

            function getProp(id,serviceId){
                let productList = [];
                $.get(`/energy/iot/getServicePropList/${id}`,function(data,status){
                    if(data.code == 0){
                        let jsonItem ={};
                        let body={};
                        let token ='token???';
                        let timestamp = getNowTime();
                        jsonItem['token'] = token;
                        jsonItem['timestamp'] = timestamp;
                        body['serviceId'] = serviceId;
                        body['serviceProperties'] = data.data.serviceProperties;
                        jsonItem['body'] = body;
                        jsonBodyStr = JSON.stringify(jsonItem, null, 4)
                        // $('#data').empty();
                        // $('#data').append(jsonBodyStr);
                        $('#data').val("");
                        $('#data').val(jsonBodyStr);
                        propList = data.data.propList;
                        controller();
                    }else{
                        layer.msg("product信息解析失败", function(){
                        });
                    }
                });
            };

            //执行一个 table 实例================================
            table.render({
                elem: '#iot'
                // ,height: 420
                ,url: '/energy/iot/list2' //数据接口
                ,title: '设备产品'
                ,page: false //开启分页
                ,toolbar: true
                ,data: []
                ,toolbar: '#ksla4' //开启工具栏，此处显示默认图标，可以自定义模板，详见文档
                ,cols: [[ //表头
                    {type: 'numbers', title: '序号', align: 'center', width: 100, fixed: 'left'}
                    ,{field: 'id', title: 'id',  width: 150,align: 'center',fixed: 'left'}
                    ,{field: 'productId', title: '产品id',  width: 150,align: 'center',fixed: 'left'}
                    , {field: 'manufacturerId', width: 150,title: 'manufacturerId', align: 'center'}
                    , {field: 'manufacturerName', width: 150,title: 'manufacturerName', align: 'center'}
                    , {field: 'model', width: 150,title: 'model', align: 'center'}
                    , {field: 'deviceName', width: 150,title: 'deviceName', align: 'center'}
                    , {field: 'nodeId', width: 150,title: 'nodeId', align: 'center'}
                    , {field: 'model', width: 150,title: 'model', align: 'center'}
                    , {field: 'deviceType', width: 150,title: 'deviceType', align: 'center'}
                    , {field: 'protocolType', width: 150,title: 'protocolType', align: 'center'}
                    , {field: 'status', width: 150, templet: setStatus,title: '状态', align: 'center'}
                    , {title: '操作',width: 380, templet: setOperates, align: "center"}
                    // ,{fixed: 'right', width: 150, align:'center', toolbar: '#barDemo'}
                ]]
            });
            //执行一个 table 实例================================
            //table行选中
            table.on('row(iot)', function (obj) {//datafilter是table的lay-filter属性
                console.log(obj.data);
                $('.success').removeClass('success'); //去除之前选中的行的，选中样式
                $(obj.tr).addClass('success'); //添加当前选中的 success样式用于区别
                getIotProductService(obj.data.productId,obj.data.serviceId);
            });
            //监听工具条========================================
            function setOperates(data) {
                let id = data.id
                    ,status = data.status
                    ,statusStr = "上线"
                    ,disabled = ""
                    ,sendStr = ""
                    ,color = "layui-btn-primary"
                    ,color2 = "layui-btn-primary"
                    ,onlineStatus = data.onlineStatus
                    ,sendStatus = data.sendStatus;

                if(onlineStatus == 0){
                    statusStr = "上线【开启心跳定时任务】";
                    color = "#layui-btn-green";
                }else{
                    statusStr = "下线【关闭心跳定时任务】";
                    color = "layui-btn-danger";
                }



                if(sendStatus == 0){
                    sendStr = "启动模拟数据定时任务";
                    color2 = "layui-btn-green";
                }else{
                    sendStr = "关闭模拟数据定时任务";
                    color2 = "layui-btn-danger";
                }

                var btn = "";
                btn += `<a  lay-event="online" class="layui-btn layui-btn-xs ${color}" )">${statusStr}</a> `
                btn += `<a  lay-event="start" class="layui-btn layui-btn-xs  ${color2}" )">${sendStr}</a>`
                return btn;
            };
            function setStatus(data) {
                var status = data.status;
                var color = "#000";
                /*console.log(yitableid + "dgdgd");*/
                if(status == 'OFFLINE'){
                    color = "layui-badge";
                }else if (status == 'ONLINE') {
                    color = "layui-bg-green";
                }else {
                    color = "layui-bg-orange";
                }
                var btn = "";
                btn += `<!--<span style="font-size:15px;font-weight:800;color:${color}">${status}</span>-->`
                btn += `<span class="layui-badge ${color}">${status}</span>`
                // btn += `<a class="layui-btn layui-btn-xs" lay-event="more">${status} <i class="layui-icon layui-icon-down">`;
                console.log(btn);
                return btn;
            }
            //监听行工具条========================================

            //监听行工具事件=============================================================
            table.on('tool(iot)', function(obj){ //注：tool 是工具条事件名，test 是 table 原始容器的属性 lay-filter="对应的值"
                let layEvent = obj.event; //获得 lay-event 对应的值
                if(layEvent === 'online'){
                    online(obj);
                } else if(layEvent === 'start'){
                    start(obj);
                }
            });
            //监听单元格事件=============================================================

            //心跳定时任务=============================================================
            function online(obj){
                console.log("online");
                let data = obj.data //获得当前行数据
                    ,status = data.status
                    ,action = -1
                    ,statusStr = "上线"
                    ,color = "layui-btn-primary"
                    ,onlineStatus = data.onlineStatus;

                if (onlineStatus == 1) {
                    statusStr = "下线";
                    action = 0;
                    layer.confirm('确定要移除心跳定时任务吗？', function(index){
                        let jsonData = {
                            "iotDeviceEntity": data,
                            "action": action,
                        };
                        ajax("/energy/iot/task/taskStartOrRemove",jsonData,function (data, status) {
                            if (data.code == 0) {
                                layer.msg("启动成功");
                                table.reload('iot');
                            } else {
                                layer.msg("启动失败:"+data.msg, function(){
                                });
                            }
                        });
                        layer.close(index);
                    });
                }else if (onlineStatus == 0) {
                    statusStr = "上线";
                    action = 1;
                    layer.open({
                        id:1,
                        type: 1,
                        title:'请输入cron表达式(心跳间隔)',
                        style: 'width:50px;height:30px;',
                        content: `<div style='margin:20px;display:flex;justify-content:center;'><textarea id='area' style='width:100%;height:135px;'>0/10 * * * * ?</textarea></div>`,
                        btn:['确定','取消'],
                        yes:function (index,layero) {
                            //获取输入框里面的值
                            var closeContent = top.$("#area").val() || $("#area").val();
                            if(closeContent){
                                console.log(closeContent);
                            }
                            layer.close(index);
                            // 在这里提交数据
                            let jsonData = {
                                "iotDeviceEntity": data,
                                "cron" :closeContent,
                                "action": action
                            };
                            ajax("/energy/iot/task/taskStartOrRemove",jsonData,function (data, status) {
                                if (data.code == 0) {
                                    layer.msg("启动成功");
                                    table.reload('iot');
                                } else {
                                    layer.msg("启动失败:"+data.msg, function(){
                                    });
                                }
                            });
                        },
                        no:function (index,layero) {
                            layer.close(index);
                        }
                    });
                }


            };
            //=============================================================

            //数据发送定时任务  ==============================================================
            function start(obj){
                console.log("start");
                let data = obj.data //获得当前行数据
                let status = data.status,
                    sendStatus = data.sendStatus;
                if (sendStatus === 0){
                    //表单参数组装===========================
                    let jsonBody = getParseJson()
                    let serviceId = document.getElementById("serviceId_parse").value;
                    // return;
                    //======================================
                    layer.open({
                        id:1,
                        type: 1,
                        title:'请输入cron表达式(数据发送间隔)',
                        style: 'width:50px;height:auto;',
                        content: `<div style='margin:20px;display:flex;justify-content:center;'><textarea id='area2' style='width:100%;height:135px;'>0/2 * * * * ?</textarea></div>`,
                        btn:['确定','取消'],
                        yes:function (index,layero) {
                            //获取输入框里面的值
                            var closeContent = top.$("#area2").val() || $("#area2").val();
                            if(closeContent){
                                console.log(closeContent);
                                // 在这里提交数据
                                let jsonData = {
                                    "iotDeviceEntity": data,
                                    "cron" :closeContent,
                                    "serviceId":serviceId,
                                    "message":JSON.stringify(jsonBody),
                                    "action": 1
                                };
                                ajax("/energy/iot/task/sendMessages",jsonData,function (data, status) {
                                    if (data.code == 0) {
                                        layer.msg("启动成功");
                                        table.reload('iot');
                                    } else {
                                        layer.msg("启动失败:"+data.msg, function(){
                                        });
                                    }
                                });
                                layer.close(index);
                            }
                        },
                        no:function (index,layero) {
                            layer.close(index);
                        }
                    });

                }else{
                    layer.confirm('确定要移除数据发送定时任务吗？', function(index){
                        let jsonData = {
                            "iotDeviceEntity": data,
                            "action": 0
                        };
                        ajax("/energy/iot/task/sendMessages",jsonData,function (data, status) {
                            if (data.code == 0) {
                                layer.msg("移除成功");
                                table.reload('iot');
                            } else {
                                layer.msg("移除失败:"+data.msg, function(){
                                });
                            }
                        });
                        layer.close(index);
                    });

                }
            }
            //==========================================================
        });
    });

    function selectChange(obj,val){
        obj.value = val.value;
    };
    function openIotJsonList(){
        //iframe层-父子操作
        layer.open({
            type: 2,
            area: ['850px', '700px'],
            fixed: false, //不固定
            // maxmin: true,
            content: '/iot'
        });
    };
    function check(title,jsonBody,jsonParse){
        if(!title){
            layer.msg("请输入标题", function(){
            });
            return false;
        }
        if(!jsonBody){
            layer.msg("请输入jsonBody", function(){
            });
            return false;
        }
        if(!jsonParse){
            layer.msg("请输入jsonParse", function(){
            });
            return false;
        }
        if(!isJSON(jsonParse)){
            layer.msg("jsonParse请输入正确的json格式", function(){
            });
            return false;
        }
        if(!isJSON(jsonBody)){
            layer.msg("jsonParse请输入正确的json格式", function(){
            });
            return  false;
        }
        return true;
    }
    function saveJson(){
        layer.open({
            id:1,
            type: 1,
            title:'请输入模板标题',
            style: 'width:50px;height:auto;',
            content: `<div style='margin:20px;display:flex;justify-content:center;'><input id="titleModel" type="text" name="titleModel" autocomplete="off" placeholder="请输入标题" class="layui-input"></div>`,
            btn:['确定','取消'],
            yes:function (index,layero) {
                //获取输入框里面的值
                var title = top.$("#titleModel").val() || $("#titleModel").val();
                if(title){
                    // 在这里提交数据
                    let json={}
                    jsonBodyStr = $('#data').val();
                    let jsonBody = JSON.stringify(JSON.parse(jsonBodyStr));
                    let jsonParse = JSON.stringify(getParseJson());
                    check(title,jsonBody,jsonParse);
                    let serviceId = JSON.parse(jsonBody).body.serviceId;
                    if(serviceId==undefined||serviceId==null){
                        layer.msg("json未正常解析得到serviceId，请确认是否输入正确！", function(){
                        });
                        return;
                    }
                    let data ={
                        title:title,
                        serviceId:serviceId,
                        jsonBody:jsonBody,
                        jsonParse:jsonParse
                    }
                    console.log(data);
                    ajax('/iot/parse/save',data,function(data,status){
                        console.log(data);
                        if (data.code == 0) {
                            layer.msg("保存成功");
                            table.reload('iot');
                        } else {
                            layer.msg("启动失败:"+data.msg, function(){
                            });
                        }
                    });
                    layer.close(index);
                }else{
                    layer.msg("请输入模板标题", function(){
                    });
                }

            },
            no:function (index,layero) {
                layer.close(index);
            }
        });

    };
    function getParseJson(){
        let jsonBody = {};
        let div = document.getElementById("f1");
        // let serviceId = document.getElementById("serviceId_parse").value;
        let forms = div.getElementsByTagName('form');

        for (let i = 0; i < forms.length; i++) {
            let name =forms[i].id;
            let tagElements = forms[i].getElementsByTagName('input');
            let enumFlag = false;
            let json = {};
            for (var j = 0; j < tagElements.length; j++) {
                let _name = tagElements[j].name;

                let value = tagElements[j].value;
                if(tagElements[j].type == 'checkbox'){
                    let itemName ="enable"
                    let checkName = tagElements[j].name;
                    if(checkName.includes("enum")){
                        itemName = "enum_enable";
                    }
                    if(tagElements[j].checked){
                        json[itemName] = 1;
                        if(itemName == "enum_enable"){
                            enumFlag = true;
                        }
                    }else{
                        json[itemName] = 0;
                    }
                }else{
                    if(_name.indexOf("random_min_")==0){
                        json["min"] = value;
                    }else if(_name.indexOf("random_max_")==0){
                        json["max"] = value;
                    }else if(_name.indexOf("default_")==0){
                        json["default"] = value;
                    }else if(_name.includes("trend")){
                        json["trend"]= value;
                    }else if(_name.includes("size")){
                        json["size"]= value;
                    }else if(_name.includes("dataType")){
                        json["dataType"]= value;
                    }
                }

                if(enumFlag){
                    let id = forms[i].getElementsByTagName('select')[0].id;
                    if ($("#"+id+" option").length >0){
                        let enumList = [];
                        $("#"+id+" option").each(function(){
                            enumList.push($(this).val());
                        });
                        json["enum"] = enumList;
                    }
                }
            }
            jsonBody[name] = json;
        }
        console.log("jsonBody",jsonBody);
        console.log(JSON.stringify(jsonBody));
        return jsonBody;
    };
    function addEnumInput(modname,obj){
        let id ="random_enable_enumList_"+modname.id;
        if(obj.innerHTML == "添加枚举值"){
            let html = `<input  style="width: 50px;" type="number" id="${'add_value_'+modname.id}" value="">`
                + `<a style="background-color: #155037"  id="${'add_yes_'+modname.id}" class="layui-btn layui-btn-xs layui-btn-normal" onclick="addEnum(this)">确定</a>`
            $(obj).parent().append(html);
            $('#add_yes_'+modname.id).attr('forAttr',modname.id);
            obj.innerHTML = "取消";
        }else{
            $(obj).parent().find('#add_value_'+modname.id).remove();
            $(obj).parent().find('#add_yes_'+modname.id).remove();
            obj.innerHTML = "添加枚举值";
        }
    };
    function addEnum(obj){
        console.log(obj);
        let id = $(obj).attr("forAttr");
        let enumAttr = $("#add_value_"+id).val();
        if (enumAttr == ""||enumAttr == null||enumAttr.length == 0){
            layer.msg("请输入枚举值", function(){
            });
        }else{
            let html = `<option value="${enumAttr}">${enumAttr}</option>`;
            let returnFlag = false;
            $('#random_enable_enumList_select_'+id+" option").each(function(){
                if ($(this).val() == enumAttr){
                    layer.msg("枚举值已存在", function(){
                    });
                    returnFlag = true;
                    return false;
                }
            });
            if (returnFlag){
                return;
            }
            $('#random_enable_enumList_select_'+id).append(html);
            $(obj).parent().find('#add_value_'+id).remove();
            $(obj).parent().find('#add_yes_'+id).remove();
            $('#add_'+id).html("添加枚举值") ;
            layer.msg("添加成功");
        }
    };
    function ajax(url,data,callback){
        $.ajax({
            dataType:'json',
            contentType: "application/json; charset=utf-8",
            url: url,
            type: "POST",
            data: JSON.stringify(data),
            // data: data,
            success: function (data, status) {
                callback(data,status);
            },
            error:function(msg) {     //请求失败后要执行的代码
                alert("请求失败"+msg);
            }
                // success: function (data) {
            //     if (data.code == 0) {
            //         layer.msg("启动成功");
            //         table.reload('iot');
            //     } else {
            //         layer.msg("启动失败:"+data.msg, function(){
            //         });
            //     }
            // }
        });
    }
    //获取当前时间
    function getNowTime() {
        var date = new Date();
        //年 getFullYear()：四位数字返回年份
        var year = date.getFullYear();  //getFullYear()代替getYear()
        //月 getMonth()：0 ~ 11
        var month = date.getMonth() + 1;
        //日 getDate()：(1 ~ 31)
        var day = date.getDate();
        //时 getHours()：(0 ~ 23)
        var hour = date.getHours();
        //分 getMinutes()： (0 ~ 59)
        var minute = date.getMinutes();
        //秒 getSeconds()：(0 ~ 59)
        var second = date.getSeconds();

        var time =  year + '-' + addZero(month) + '-' + addZero(day) + ' ' + addZero(hour) + ':' + addZero(minute) + ':' + addZero(second);
        return time;
    }
    //小于10的拼接上0字符串
    function addZero(s) {
        return s < 10 ? ('0' + s) : s;
    }

    function isJSON(str) {
        if (typeof str == 'string') {
            try {
                var obj=JSON.parse(str);
                if(typeof obj == 'object' && obj ){
                    return true;
                }else{
                    return false;
                }

            } catch(e) {
                return false;
            }
        }
    }


    function fromSonParse(data){
        jsonParse = JSON.parse(data.jsonParse);
        let list =[];
        for(var item in jsonParse){
            let json = jsonParse[item];
            json['propertyName'] = item;
            if(json['enum']!= undefined&&json['enum']!=null){
                json['enumList'] =JSON.stringify(json['enum']);
            }
            list.push(json);
        }
        let body =JSON.parse(data.jsonBody);
        for(var item in body.body.serviceProperties){
            body.body.serviceProperties[item] =jsonParse[item].default
        }
        propList = list;
        $('#data').val(JSON.stringify(body, null, 2));
        controller();
    }



</script>
</body>

</html>



